<template>
    <!-- 卡片 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <!-- 头部按钮 -->
        <template #header>
            <el-button type="primary" size="default" :icon="Plus" @click="addTrademark">添加</el-button>
        </template>
        <!-- 表格 -->
        <el-table style="margin-bottom: 30px" :data="tabelData"  stripe border>
          <el-table-column align="center" type="index" label="序号" width="80"></el-table-column>
          <el-table-column prop="tmName" label="品牌名称"></el-table-column>
          <el-table-column prop="logoUrl" label="品牌LOGO">
            <template #default="{row}">
              <img :src="row.logoUrl" height="80" alt=""/>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="warning" :icon="Edit" @click="updateTrademark(row)">修改</el-button>
              <el-button type="danger" :icon="DeleteFilled" @click="deleteTrademark(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 页码 -->
        <el-pagination 
            v-model:current-page="page" 
            v-model:page-size="limit"
            :pager-count="7"
            :total="total"
            :page-sizes="[3, 5, 7, 10]"
            layout="prev, pager, next , sizes, total"
        ></el-pagination>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog  v-model="dialogFormVisible" :title="newTrademark.id? '修改商品' : '新增商品' ">
      <!-- 表单 -->
      <el-form label-width="100px" :model="newTrademark" :rules="TrademarkRules" ref="fromEle">
        <!-- 输入框 -->
        <el-form-item label="品牌名称" prop="tmName">
          <el-input autocomplete="off"  v-model="newTrademark.tmName"/>
        </el-form-item>
        <!-- 上传图片 -->
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/admin/product/upload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload> 
        </el-form-item>
      </el-form>
      <!-- 按钮 -->
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="updateOrAddTrademark">确认</el-button>
      </span>
      </template>
    </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
    name: "Trademark",
});
</script>

<script setup lang="ts">
import {Plus , Edit , DeleteFilled} from '@element-plus/icons-vue'
import {ref , toRefs , onMounted , watch ,reactive} from "vue"
import {requestTrademarkList , requestUpdateTrademark , requestAddTrademark , requestDeleteTrademark} from "@/api/tradmark"
import type {reqTrademarkReturnRecordsType , reqTrademarkReturnItemType} from "@/api/tradmark"
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadProps , FormRules , FormInstance} from 'element-plus'

//1.table逻辑 table数据
const tabelData = ref<reqTrademarkReturnRecordsType>([]);

//2.页码逻辑
//页码的数据和类型
interface pageDateType{
    page: number
    limit: number
    total: number
}
const pageDate = ref<pageDateType>({
    page: 1,
    limit: 3,
    total: 100
})
//解构页码数据
const {page , limit , total} = toRefs(pageDate.value)


//3.获取品牌列表
//封装获取品牌列表的功能函数
const getTrademarkList = async() => {
  //发送请求
  const result = await requestTrademarkList({page: page.value , limit: limit.value})
   //把请求回来的数据设置给响应
   tabelData.value = result.records
   total.value = result.total
}
//初始化
onMounted(() => {
  //调用获取品牌列表的功能函数
  getTrademarkList();
});
//监听page,limit改变发送请求
watch([page , limit] , () => {
  //每次修改页码重新发送请求
  getTrademarkList();
})


//4.弹窗逻辑
//控制弹窗显示隐藏的数据
const dialogFormVisible = ref(false);
//添加文件要请求的前缀  
const baseUrl = import.meta.env.VITE_API_URL;
//定义一个新的要添加的对象
const newTrademark = ref<reqTrademarkReturnItemType>({
  logoUrl: "",
  tmName: "",
  id: 0,
})

//上传文件成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  //把上传图片成功之后，响应的图片地址给数据保存起来
  newTrademark.value.logoUrl = response.data;
   //上传成功之后清空上一次残留的校验信息
   fromEle.value?.clearValidate("logoUrl")
}
//上传文件之前的回调
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

//5.添加逻辑
const addTrademark = () => {
  //添加之前清空上一次可能残留的校验信息
  fromEle.value?.clearValidate()
  //展示弹窗
  dialogFormVisible.value = true
  //清空弹窗数据
  newTrademark.value = {
    logoUrl: "",
    tmName: "",
    id: 0,
  }
}

//6.点击修改的逻辑
const updateTrademark = async (row: reqTrademarkReturnItemType) => {
  //修改之前清空上一次可能残留的校验信息
  fromEle.value?.clearValidate()
  //展示弹窗
  dialogFormVisible.value = true
  //获取当前的数据然后进行回填数据
  //拿到当前的数据浅拷贝赋值给表单的数据newTrademark(为了数据不会互相影响)
  newTrademark.value = {...row}
}

//7.新增和修改提交
//拿到表单实例
const fromEle = ref<FormInstance>()
const updateOrAddTrademark = async () => {
  try {
    //提交之前进行全局表单校验
    await fromEle.value?.validate()

    //表单校验成功了才执行提交逻辑
    //关闭弹窗
    dialogFormVisible.value = false
    try {
      //判断是修改还是新增
      if(newTrademark.value.id){
        //修改提交
        await requestUpdateTrademark(newTrademark.value);
        ElMessage.success("修改成功");
      }else{
        //新增提交
        await requestAddTrademark(newTrademark.value);
        ElMessage.success("新增成功");
        //新增成功后回到第一页
        page.value = 1
      }
      //修改或者新增成功都重新请求商品列表
      getTrademarkList()
    }catch(e) {
      ElMessage(newTrademark.value.id? '修改失败' : '新增失败')
    }

  } catch (error) {
    ElMessage.error("表单校验失败")
  }

}

//8.删除逻辑
const deleteTrademark = (id:number) => {
  //点击删除弹出选择框 
  ElMessageBox.confirm("确定要删除吗?" , "警告！" , {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
  })
  .then( async ()=>{
    //点击确定执行删除逻辑
    try {
      //发送删除请求
      await requestDeleteTrademark(id)
      //删除成功提示
      ElMessage.success("删除成功!!!")
      //删除成功重新请求商品列表
      getTrademarkList()
    }catch(e) {
      //删除失败提示
      ElMessage.error("删除失败")
    }
  })
  .catch(()=>{
    //点击取消，关闭消息提示框
    ElMessage.info("不吃别扒拉!")
  })
}

//9.添加或删除商品的表单校验规则
//自定义校验规则
const inputLangRuler = (rule: any, value: string, callback: any) => {
  if(value.length < 2 || value.length > 5){
    callback("输入内如不合法")
  }else{
    callback();
  }
};
//表单校验规则
const TrademarkRules = reactive<FormRules>({
  tmName:[
    { required: true, message: '输入内容不能为空!', trigger: 'blur' },
    //自定义表单校验规则
    { validator:inputLangRuler ,  trigger: 'blur' },
  ],
  logoUrl:[{ required: true, message: "必须上传图片", trigger: "change" }],
})

</script>

<style scoped >
  .el-button--text {
    margin-right: 15px;
  }
  .el-select {
    width: 300px;
  }
  .el-input {
    width: 300px;
  }
  .dialog-footer button:first-child {
    margin-right: 10px;
  }


  .avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>